package com.web;

import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet{
    UserService userService= new UserServiceImpl();
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username =req.getParameter("username");
        String password =req.getParameter("password");
        String email = req.getParameter("email");
        String code =req.getParameter("code");
        User user =WebUtils.copyParamToBean(req.getParameterMap(),new User());
        String token=(String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if (token!=null&&token.equalsIgnoreCase(code)){
            if (userService.existsUsername(user.getUsername())){
                System.out.println("用户名存在！");
                req.setAttribute("msg","用户名存在啦！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else {
                userService.registerUser(user);
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else {
            System.out.println("验证码错误！");
            req.setAttribute("msg","嗨害(｡･∀･)ﾉﾞ嗨！验证码错误啦");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User loginuser = userService.login(new User(null,username,password,null));
        if (loginuser!=null){
            req.getSession().setAttribute("user",loginuser);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg","用户名或密码错误啦！！！");
            req.setAttribute("username",username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }
}
